﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using Game;
using System;

[RequireComponent(typeof(Text))]
public class LanguageText : MonoBehaviour , ILanguageText
{
    public Text Text;
    
    public bool WithID;
    public int ID;
    public string Key;

    public string Value 
    {
        get =>  Text.text; 
        set { Text.text = value; }

    }

    private RofLanguageRow _rofLanguageRow;

    public void SetLanguageByID(int id) 
    {
        ID = id;
        WithID = true;
        RefreshLanguage();
    }

    public void SetLanguageByKey(string key) 
    {
        if (key == null)
        {
            return;
        }
        Key = key;
        WithID = false;
        RefreshLanguage();
    }

    private void OnEnable()
    {
        ComponentCheck();
        RefreshLanguage();
        LanguageManager.Instance.Regist(this);
    }

    private void OnDisable()
    {
        LanguageManager.Instance.UnRegist(this);
    }

    public void UpdateLanguageData() 
    {
        if (_rofLanguageRow == null)
        {
            this._rofLanguageRow = WithID ? LanguageManager.Instance.GetLanguageDataByID(ID) : LanguageManager.Instance.GetLanguageData(Key);
        }
        else if (_rofLanguageRow.ID != ID && !_rofLanguageRow.Key.Equals(Key, StringComparison.OrdinalIgnoreCase))
        {
            this._rofLanguageRow = WithID ? LanguageManager.Instance.GetLanguageDataByID(ID) : LanguageManager.Instance.GetLanguageData(Key);
        }
    }

    public void UpdateText() 
    {
        Text.text = LanguageManager.Instance.ToLanguageStr(_rofLanguageRow);
    }

    public void RefreshLanguage() 
    {
        UpdateLanguageData();
        UpdateText();
    }

    public void ComponentCheck() 
    {
        if (Text == null)
        {
            Text = this.gameObject.GetComponent<Text>();
        }
    }
}
